<template>
    <n-collapse-transition v-if="visible">
        <div class="img-preview-wrapper" v-if="visible">
            <div class="tip-wrapper">

                <div class="name" :title="activeImageName">
                    {{ activeImageName }}
                </div>
                <div class="opera-btn-group">
                    <n-input-number
                        v-model:value ="inputActiveIndex"
                        :min="0"
                        :max="imgList.length"
                        :on-update:value ="handleChangeInputIndex"
                    ></n-input-number>
                    <span class="split-line">/</span>{{ imgList.length - 1 }}
                </div>
                <div class="tool-wrapper">
                    <n-icon
                        class="item el-icon-refresh-right"
                        title="向右旋转"
                        @click="handleRotateImg"
                    >
                    <reload-sharp></reload-sharp>
                    </n-icon>
                    <a
                        target="_blank"
                        :href="activeDownloadLink"
                        :download="activeImageName"
                    >
                        <n-icon class="item" title="保存到本地">
                            <cloud-download-sharp></cloud-download-sharp>
                        </n-icon>

                    </a>
<!--                    <n-tooltip effect="dark" placement="bottom">-->
<!--                        <div slot="content" style="line-height: 1.5">-->
<!--                            1. 点击图片以外的区域可退出预览<br />-->
<!--                            2. 按 Escape 键可退出预览<br />-->
<!--                            3. 按左、右方向键可切换为上一张、下一张图片<br />-->
<!--                            4. 鼠标滚轮可放大、缩小图片<br />-->
<!--                            5. 点击左上角-->
<!--                            <i class="el-icon-d-arrow-left"></i> 图标可折叠、展开缩略图<br />-->
<!--                        </div>-->
<!--                        <div class="item text-wrapper">-->
<!--                            <span class="text">操作提示</span>-->
<!--                            <i class="el-icon-s-opportunity"></i>-->
<!--                        </div>-->
<!--                    </n-tooltip>-->
                    <i
                        class="item close-icon el-icon-close"
                        title="关闭预览"
                        @click="handleCloseImgPreview"
                    ></i>
                </div>
            </div>
            <!-- 左侧缩略图 -->
            <ul class="min-img-list" ref="minImgListRef">
                <li
                    :ref="minImgLi"
                    class="min-img-item"
                    v-for="(item, index) in imgList"
                    :key="index"
                    :class="{ active: activeIndex === index }"
                    :title="fileFunction.getFileNameComplete(item)"
                    @click="activeIndex = index"
                >
                    <n-image
                        class="min-img"
                        :src="fileFunction.setFileImg(item)"
                        :alt="`${item.fileName} 缩略图`"
                        preview-disabled
                    >
                    </n-image>
                </li>
            </ul>
            <!-- 右侧预览区域 -->
            <div
                class="img-wrapper"
                @mousewheel.prevent="handleMouseWheel()"
                @click.self="handleCloseImgPreview"
            >
                <!-- 大图查看 -->
                <n-image
                    class="img-large"
                    :ref="imgLargeList"
                    v-for="(item, index) in imgList"
                    :key="index"
                    :src="item.fileUrl"
                    v-show="index === activeIndex"
                    :style ="{zoom: `${imgZoom}%`,transform: `rotate(${rotate}deg)`}"
                    preview-disabled
                />
                <!-- 左右切换图标 -->
                <n-icon
                    class="pre-icon el-icon-arrow-left"
                    title="上一张"
                    v-show="activeIndex > 0"
                    @click.stop="handleChangeActiveImg(activeIndex - 1)"
                >
                    <chevron-back-outline/>
                </n-icon>
                <n-icon
                    class="next-icon el-icon-arrow-right"
                    title="下一张"
                    v-show="activeIndex < imgList.length - 1"
                    @click.stop="handleChangeActiveImg(activeIndex + 1)"
                >
                    <chevron-forward-outline/>
                </n-icon>
                <!-- 底部显示放大缩小比例 -->
                <div class="zoom-bar">
                    <n-slider
                        v-model:value="imgZoom"
                        :min="imgZoomMin"
                        :max="imgZoomMax"
                        :format-tooltip="formatZoomSize"
                        :on-update:value="handleZoomImg"
                    ></n-slider>
                    <div class="zoom-count">{{ imgZoom }}%</div>
                </div>
            </div>
        </div>
    </n-collapse-transition>
</template>

<script lang="ts" setup>
import {computed, ref} from "vue";
//@ts-ignore
import fileFunction from '@/libs/globalFunction/file.js'
import { ChevronBackOutline, ChevronForwardOutline,ReloadSharp,CloudDownloadSharp} from '@vicons/ionicons5'
import {storeToRefs} from "pinia";
import {useUserStore} from "@/store/modules/useUserStore";
import {store} from "@/store";
import {storage} from "@/hooks/useStorage";
const {authorization,tokenKey} = storeToRefs(useUserStore(store));
const token = authorization?.value ?? storage.get(tokenKey?.value);

const visible = ref(false)
const activeIndex = ref(0)
const inputActiveIndex =ref(1)
const rotate = ref(0)

const imgZoom = ref(100) //  图片缩放比例
const imgZoomMin = ref(10) //  图片缩放最小比例
const imgZoomMax = ref(210) //  图片缩放最大比例


const minImgListRef = ref(null)
const minImgRef = []
const minImgLi = (el:any) =>{
    minImgRef.push(el)
}

const imgLarge = []
const imgLargeList = (el:any)=>{
    imgLarge.push(el)
}

let imgList: any[] = []
let defaultIndex = 0



const activeImage = computed(() => {
  return imgList[activeIndex.value]
})

const activeImageName = computed(() => {
  return fileFunction.getFileNameComplete(activeImage.value)
})

// 当前显示的图片下载链接
const activeDownloadLink = computed(() =>{
  return activeImage.value.downloadLink +"&token="+token
})


/**
 * 数据改变时触发（使用鼠标拖曳时，活动过程实时触发）
 * @param {number} value 缩放数字
 */
const handleZoomImg = (value:number) => {
  if (imgLarge) {
    imgZoom.value = value
    imgLarge[inputActiveIndex.value].$el.style.zoom = value + '%' //  实时设置图片缩放比例
  }
}


/**
 * 格式化 tooltip message - 显示图片缩放比例
 * @param {number} value 缩放数字
 * @returns {string}  图片缩放比例
 */
const formatZoomSize = (value:number) => {
  return value + '%'
}

/**
 * 鼠标滚动事件
 * @description 缩放图片
 */
const handleMouseWheel = () =>{
  let zoom =
      parseInt(imgLarge[activeIndex.value].$el.style.zoom) || 100
  zoom += event.wheelDelta / 12
  if (zoom >= imgZoomMin.value && zoom < imgZoomMax.value) {
    imgZoom.value = zoom
    console.log(imgLarge[activeIndex.value].$el)
    imgLarge[activeIndex.value].$el.style.zoom = zoom + '%'
  }
  return false
}


/**
 * 关闭图片预览，恢复旋转角度
 */
const handleCloseImgPreview = () =>{
    imgList = []
    defaultIndex = 0
    visible.value = false
}

/**
 * 旋转图片
 */
const handleRotateImg = () =>{
  rotate.value += 90
}


/**
 * 顶部栏输入框绑定值被改变时触发
 * @param {number} currentValue 当前值
 */
const handleChangeInputIndex = (currentValue:number) => {
  inputActiveIndex.value = currentValue -1
  activeIndex.value = currentValue - 1
  handleChangeActiveImg(currentValue - 1)
}


/**
 * 改变当前查看的图片索引
 */
const handleChangeActiveImg = (index:number) =>{
  if (index >= 0 && index < imgList.length) {
    activeIndex.value = index
    inputActiveIndex.value = index
    handleScrollMinImg()
  }
}


/**
 * 将缩略图中当前查看的图片缩略图滚动到视野中
 */
const handleScrollMinImg = () => {
  const parentEle = minImgListRef //  包裹缩略图的父元素
  const activeEle = minImgRef[activeIndex.value] //  当前缩略图
  // 当前元素距离可视区域顶部的距离
  const currentEleTop = activeEle.offsetTop - activeEle.clientHeight
  // 当前元素距离可视区域底部的距离
  const currentEleBottom = parentEle.clientHeight - activeEle.offsetTop
  // 如果当前查看的图片缩略图有一部分在可视区域之外（之上或之下）
  if (
      currentEleBottom < activeEle.clientHeight ||
      currentEleTop < activeEle.clientHeight
  ) {
    // 将父元素的滚动条向可视区域方向滚动两个图片的高度
    parentEle.scrollTop = -currentEleBottom + activeEle.clientHeight * 2
  }
}


const showPreview =(imgList_:any,currentIndex_:number) =>{
    console.log(imgList)
    imgList = imgList_

    defaultIndex = currentIndex_
    if(imgList_.length <= currentIndex_){
        defaultIndex = 0
    }
    activeIndex.value = defaultIndex
    inputActiveIndex.value = defaultIndex
    visible.value = true
}

// const hidePreview = () =>{
//   visible.value = false
// }

defineExpose({
  showPreview,
  // hidePrewview
})


</script>

<style lang="stylus" scoped>

.img-preview-wrapper {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  overflow: auto;
  width: 100%;
  height: 100%;
  z-index: 2;
  text-align: center;
  display: flex;
  align-items: center;
  animation: imgPreviewAnimation 0.3s;
  animation-iteration-count: 0.3;
  animation-fill-mode: forwards;

  @keyframes imgPreviewAnimation {
    0% {
      background: transparent;
    }

    100% {
      background: rgba(0, 0, 0, 0.9);
    }
  }

  .tip-wrapper {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 2;
    background: rgba(0, 0, 0, 1);
    padding-right: 48px;
    width: 100%;
    height: 48px;
    line-height: 48px;
    color: #fff;
    font-size: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .fold-icon {
      margin-right: 16px;
      font-size: 24px;
      cursor: pointer;
      &:hover {
        opacity: 0.6;
      }
      &.no-fold {
        width: 120px;
      }
      &.fold {
        width: 64px;
      }
    }

    .name {
      flex: 1;
      padding-right: 16px;
        margin-left : 20px;
      text-align: left;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .opera-btn-group {
      width: 120px;
      display: flex;


      .split-line {
        margin: 0 8px;
      }
    }

    .tool-wrapper {
      flex: 1;
      display: flex;
      justify-content: flex-end;
      align-items: center;

      .item {
        margin-left: 16px;
        cursor: pointer;

        &:hover {
          opacity: 0.7;
        }
      }

      .el-icon-refresh-right,
      .close-icon,
      .download-link {
        font-size: 18px;
      }

      .download-link {
        color: inherit;
      }

      .text-wrapper {
        margin-left: 32px;

        .text {
          margin-right: 8px;
        }
      }
    }
  }
  .min-img-list {
    position: fixed;
    top: 48px;
    left: 0;
    background: rgba(0, 0, 0, 1);
    height: calc(100vh - 48px);
    padding: 8px 16px;
    overflow-y: auto;
    list-style: none;
    setScrollbar(8px, transparent, #C0C4CC);

    .min-img-item {
      position: relative;
      margin-bottom: 4px;
      width: 80px;
      height: 80px;
      cursor: pointer;
      .min-img {
        width: 100%;
        height: 100%;
      }
      &:last-of-type {
        margin-bottom: 0;
      }
      &:not(.active)::after {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        display: block;
        width: 80px;
        height: 80px;
        background: #000;
        opacity: 0.4;
      }
      &:hover {
        &:not(.active)::after {
          opacity: 0.2;
        }
      }
    }
  }
  .img-wrapper {
    position: fixed;
    top: 48px;
    right: 0;
    left: 120px;
    overflow: auto;
    height: calc(100vh - 48px);
    display: flex;
    align-items: center;
    justify-content: center;
    &.full-width {
      left: 0;
    }
    .img-large {

    }

    .pre-icon, .next-icon {
      font-size: 60px;
      color: #fff;
      position: absolute;
      top: 50%;
      cursor: pointer;
      z-index: 3;

      &:hover {
        opacity: 0.7;
      }
    }

    .pre-icon {
      left: 64px;
    }

    .next-icon {
      right: 64px;
    }

    .zoom-bar {
      position: absolute;
      right: 0;
      bottom: 20px;
      left: 0;
      margin: 0 auto;
      width: 600px;
      display: flex;

      >>> .el-slider {
        flex: 1;

        .el-slider__bar {
          background: $PrimaryText;
        }

        .el-slider__button {
          border-color: $PrimaryText;
        }
      }

      .zoom-count {
        width: 60px;
        height: 38px;
        line-height: 38px;
        text-align: right;
        color: #fff;
      }
    }
  }

}
</style>
